package com.redmaple.config;

import com.google.common.collect.Maps;
import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author redMaple-gi
 * @Date 2020/7/2 13:31
 * @Version 1.0
 */
@Configuration
@Log4j2
@EnableConfigurationProperties(ShardingMasterSlaveConfig.class)
/** 读取ds_master 主数据源和读写分离配置 */
@ConditionalOnProperty({"sharding.jdbc.data-sources.ds_master.jdbc-url","sharding.jdbc.master-slave-rule.master-data-source-name"})
public class ShardingDataSourceConfig {

    @Autowired
    private ShardingMasterSlaveConfig shardingMasterSlaveConfig;

    @Bean
    public DataSource masterSlaveDataSource(){
        final Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources());
        final Map<String, Object> newHashMap = Maps.newHashMap();
        // 创建 MasterSlave数据源
        DataSource dataSource = null;
        try {
            dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap,
                    shardingMasterSlaveConfig.getMasterSlaveRule(), newHashMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        log.info("masterSlaveDataSource config complete");
        return dataSource;
    }
}